const Base = require('./base.js');

module.exports = class extends Base {
  indexAction() {
    return this.display();
  }

  async loginAction() {
    if (await this.hasLogin()) {
      return this.redirect('/admin');
    }

    const name = this.post('name');
    const password = this.post('password');
    const remember = this.post('remember');
    if (think.isEmpty(name) || think.isEmpty(password)) {
      return this.fail(1000, '用户名或密码不得为空');
    }

    const userService = think.service('user', 'common');
    const user = await think.model('users').where({ name: name }).find();
    if (think.isEmpty(user)) {
      return this.fail(1000, '用户名或密码错误');
    }

    if (!userService.checkPassword(password, user.password)) {
      return this.fail(1000, '用户名或密码错误');
    }

    await this.session('uid', user.uid);
    const authCode = userService.generateAuthCode();
    await think.model('users').where({uid: user.uid}).update({authCode: authCode});
    if (remember) {
      const maxAge = 30 * 24 * 3600 * 1000;
      this.cookie('__thincho_uid', user.uid.toString(), {maxAge: maxAge});
      this.cookie('__thincho_authCode', authCode, {maxAge: maxAge});
    } else {
      this.cookie('__thincho_uid', user.uid.toString());
      this.cookie('__thincho_authCode', authCode);
    }
    return this.redirect('/admin');
  }
};
